package com.alex.taskmanager.dao.memory;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;

import com.alex.taskmanager.dao.TaskData;
import com.alex.taskmanager.dao.TaskManagerDao;
import com.alex.taskmanager.dao.TaskStatus;
import com.alex.taskmanager.service.TaskManagerException;

public class InMemoryTaskManagerDao implements TaskManagerDao {

	private Collection<TaskData<?>> tasks = new LinkedList<TaskData<?>>();

	public synchronized <T> void storeTask(TaskData<T> taskData) {
		tasks.add(taskData);
	}

	@SuppressWarnings("unchecked")
	public synchronized <T> Collection<TaskData<T>> getTasks(int maxCount, int time) {
		Collection<TaskData<T>> result = new ArrayList<TaskData<T>>();
		for (TaskData<?> taskData : tasks) {
			if (taskData.getStatus() == TaskStatus.PENDING && taskData.getExecutionTime() <= time) {
				taskData.setStatus(TaskStatus.IN_PROGRESS);
				result.add((TaskData<T>) taskData);
			}
		}
		return result;
	}

	public synchronized boolean hasTasks() {
		for (TaskData<?> taskData : tasks) {
			if (taskData.getStatus() == TaskStatus.PENDING) {
				return true;
			}
		}
		return false;
	}

	public synchronized <ParamType> void updateTask(TaskData<ParamType> taskData) {
	}

	public <ParamType> void deleteTask(TaskData<ParamType> taskData) throws TaskManagerException {
		tasks.remove(taskData);
	}
}
